package com.haohan.jingyuan.user.service;

import cn.hutool.core.collection.CollectionUtil;
import cn.hutool.json.JSONUtil;
import com.haohan.jingyuan.common.enums.ErrorEnum;
import com.haohan.jingyuan.common.enums.RoleStatusEnum;
import com.haohan.jingyuan.common.exception.BusinessException;
import com.haohan.jingyuan.common.util.EntityUtil;
import com.haohan.jingyuan.gateway.holder.UserContextHolder;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.haohan.jingyuan.user.dao.RoleInfoMapper;
import com.haohan.jingyuan.user.dto.req.CreateRoleRequest;
import com.haohan.jingyuan.user.dto.req.DeleteRoleRequest;
import com.haohan.jingyuan.user.dto.req.QueryRoleListRequest;
import com.haohan.jingyuan.user.dto.req.UpdateRoleRequest;
import com.haohan.jingyuan.user.dto.resp.RoleInfoResp;
import com.haohan.jingyuan.user.dto.resp.RoleListResp;
import com.haohan.jingyuan.user.entity.RoleInfo;
import com.haohan.jingyuan.user.helper.RoleInfoRespHelper;
import com.haohan.jingyuan.util.UuidUtil;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * 角色服务实现类
 *
 * @ClassName RoleServiceImpl
 * @Description 角色相关业务逻辑实现
 * @Author hexijun
 * @Time 2025/01/19 10:25
 * @Version 1.0
 */
@Slf4j
@Service
@RequiredArgsConstructor
public class RoleService {

    private final RoleInfoMapper roleInfoMapper;

    /**
     * 创建角色
     *
     * @param request 创建角色请求
     * @return 角色信息
     */
    public RoleInfoResp createRole(CreateRoleRequest request) {

        // 检查角色是否存在
        RoleInfo existingRole = roleInfoMapper.findByRoleName(request.getRoleName());
        if (existingRole != null) {
            throw new BusinessException(ErrorEnum.ROLE_ALREADY_EXISTS);
        }

        // 创建角色信息
        RoleInfo roleInfo = new RoleInfo();
        roleInfo.setRoleId(UuidUtil.generateId("ROLE_", 4));
        roleInfo.setRoleName(request.getRoleName());
        roleInfo.setRoleStatus(RoleStatusEnum.NORMAL.getCode());
        if (CollectionUtil.isNotEmpty(request.getRoleResources())) {
            roleInfo.setRoleResources(JSONUtil.toJsonStr(request.getRoleResources()));
        }
        EntityUtil.setCreateAndModifyInfo(roleInfo, UserContextHolder.getCurrentUserName());

        // 保存到数据库
        roleInfoMapper.insert(roleInfo);

        return RoleInfoRespHelper.convertToRoleInfoResp(roleInfo);
    }

    /**
     * 更新角色
     *
     * @param request 更新角色请求
     * @return 角色信息
     */
    public RoleInfoResp updateRole(UpdateRoleRequest request) {
        // 检查角色是否存在
        Long id = Long.parseLong(request.getId());
        RoleInfo existingRole = roleInfoMapper.selectById(id);
        if (existingRole == null) {
            throw new BusinessException(ErrorEnum.ROLE_NOT_FOUND);
        }

        // 更新角色信息
        existingRole.setRoleName(request.getRoleName());
        existingRole.setRoleStatus(request.getRoleStatus() != null ? RoleStatusEnum.getByCode(request.getRoleStatus()).getCode() : existingRole.getRoleStatus());
        if (CollectionUtil.isNotEmpty(request.getRoleResources())) {
            existingRole.setRoleResources(JSONUtil.toJsonStr(request.getRoleResources()));
        }
        EntityUtil.setModifyInfo(existingRole, UserContextHolder.getCurrentUserName());

        int updateCount = roleInfoMapper.updateById(existingRole);
        if (updateCount == 0) {
            throw new BusinessException(ErrorEnum.DATABASE_ERROR);
        }

        // 重新查询更新后的角色信息
        RoleInfo updatedRole = roleInfoMapper.selectById(id);
        return RoleInfoRespHelper.convertToRoleInfoResp(updatedRole);
    }

    /**
     * 删除角色
     *
     * @param request 删除角色请求
     * @return 删除是否成功
     */
    public boolean deleteRole(DeleteRoleRequest request) {
        // 检查角色是否存在
        Long id = Long.parseLong(request.getId());
        RoleInfo existingRole = roleInfoMapper.selectById(id);
        if (existingRole == null) {
            throw new BusinessException(ErrorEnum.ROLE_NOT_FOUND);
        }

        // 逻辑删除角色
        existingRole.setIsDeleted("Y");
        EntityUtil.setModifyInfo(existingRole, UserContextHolder.getCurrentUserName());
        int deleteCount = roleInfoMapper.updateById(existingRole);

        return deleteCount > 0;
    }

    /**
     * 查询角色列表
     *
     * @param request 查询角色列表请求
     * @return 角色列表
     */
    public RoleListResp queryRoleList(QueryRoleListRequest request) {
        // 创建分页对象
        Page<RoleInfo> page = new Page<>(request.getPageNum(), request.getPageSize());

        // 分页查询
        IPage<RoleInfo> rolePage = roleInfoMapper.selectRoleListPage(page,
                request.getRoleName(), request.getRoleStatus(),
                request.getGmtCreatedStart(), request.getGmtCreatedEnd());

        // 转换为响应对象
        List<RoleInfoResp> roleList = new ArrayList<>();
        for (RoleInfo record : rolePage.getRecords()) {
            roleList.add(RoleInfoRespHelper.convertToRoleInfoResp(record));
        }

        RoleListResp response = new RoleListResp();
        response.setRoleList(roleList);
        response.setTotal(rolePage.getTotal());
        response.setPageNum(request.getPageNum());
        response.setPageSize(request.getPageSize());
        response.setTotalPages((int) rolePage.getPages());
        return response;
    }

}
